# -*- coding: UTF-8 -*-     
import tornado.ioloop
import tornado.web
import tornado.autoreload
import requests
import json 
import random
from pyquery import PyQuery as pq
import sys  

 
# tornado.web.Application(
#     debug=True
# )
 
domain = ""
if ( sys.platform == "win32"):
    domain = "http://127.0.0.1:3210/"
else:
    domain = "http://joke.machineminds.org/"

request_url = "https://www.qiushibaike.com/"
request_headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36',
    'Upgrade-Insecure-Requests' : '1',
    'Pragma' : 'no-cache',
    'Cache-Control' : 'no-cache',
    'Accept' : 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8'
}

class CrossDomain:
    def __init__(self):
        pass

    def write(self, str):
        self.set_header("Content-Type","text/html")
        self.set_header("Access-Control-Allow-Origin","*")
        self.set_header("Access-Control-Allow-Methods","GET, POST, PUT, DELETE, OPTIONS")
        self.set_header("Access-Control-Allow-Headers","Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With")
        self.write(str)

class UsersHandler(tornado.web.RequestHandler):
    def get(self, uri):
        self.render("./template/_404.html")

class ArticleHandler(tornado.web.RequestHandler):
    def get(self, uri):
        self.set_header("Content-Type","text/html")
        self.set_header("Access-Control-Allow-Origin","*")
        self.set_header("Access-Control-Allow-Methods","GET, POST, PUT, DELETE, OPTIONS")
        self.set_header("Access-Control-Allow-Headers","Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With")

        _uri = ""
        p = {}
        if uri == "/":
            _uri = ""
        else:
            _uri = uri
        
        if _uri == "" :
            self.set_header("Location", domain)
            pass

        r = requests.get(url=request_url + "article/" + _uri , headers=request_headers)
        print("request url: " + request_url + "article/" + _uri)
        r.encoding='utf8'
        html = r.text  
        if '</html>' in html:
            q = pq(html)

            article_html = q(".col1").html()
            menu_html = q("#header").html()
            list_side_html = q(".sidebar-hot.clearfix ul").html()
            hot_side_html = q(".sidebar-tag-block.tab-content0").html()

            p["title"] = "今日笑点 - 网民最爱的笑话分享社区"
            p["static"] = domain + "static/"
            p["domain"] = domain
            p["article_html"] = article_html
            p["list_side_html"] = list_side_html
            p["menu_html"] = menu_html
            p["hot_side_html"] = hot_side_html
            self.render("./template/article.html", p=p)
        else:
            pass

class MainHandler(tornado.web.RequestHandler, CrossDomain):
    def get(self, uri):
        self.set_header("Content-Type","text/html")
        self.set_header("Access-Control-Allow-Origin","*")
        self.set_header("Access-Control-Allow-Methods","GET, POST, PUT, DELETE, OPTIONS")
        self.set_header("Access-Control-Allow-Headers","Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With")

        if uri == "root.txt":
            self.set_header("Content-Type","text/text")
            self.render("./static/root.txt")
            return

        _uri = ""
        p = {}
        if uri == "/":
            _uri = ""
        else:
            _uri = uri

        r = requests.get(url=request_url + _uri , headers=request_headers)
        r.encoding='utf8'
        html = r.text 
        if '</html>' in html:
            q = pq(html)
            menu_html = q("#header").html()
            list_side_html = q(".sidebar-hot.clearfix ul").html()
            hot_side_html = q(".sidebar-tag-block.tab-content0").html()
            col1_html = q(".col1").html()
            col1_html = col1_html.replace("<div class=\"single-clear\"/>", "<div class=\"single-clear\"></div>")
            col1_html = col1_html.replace("<i/>", "<i></i>")
            p["title"] = "今日笑点 - 网民最爱的笑话分享社区"
            p["static"] = domain + "static/"
            p["domain"] = domain
            p["col1_html"] = col1_html
            p["list_side_html"] = list_side_html
            p["menu_html"] = menu_html
            p["hot_side_html"] = hot_side_html

            self.render("./template/list.html", p=p)
        else:
            pass
        # CrossDomain.write(self, newHtml) #json.dumps(_blocks, ensure_ascii=False))

class MyFile(tornado.web.StaticFileHandler):  
    def set_extra_headers(self, path):  
        self.set_header("Cache-control", "no-cache") 

def make_app():
    settings = {'debug' : False}
    return tornado.web.Application([
        (r"/images/(.*)", MyFile, {"path":"./static/images/"}),
        (r"/static/(.*)", MyFile, {"path":"./static/"}),
        (r"/article/(.*)", ArticleHandler),
        (r"/users/(.*)", UsersHandler),
        (r"/(.*)", MainHandler)
    ], settings)

if __name__ == "__main__":
    app = make_app()
    app.listen(3210)
    tornado.ioloop.IOLoop.current().start()